<?php

namespace App\Models;

use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;


class Manager extends Authenticatable
{
    use HasApiTokens, ModelTrait;

    protected $connection = 'mysql';

    protected $fillable = [
        'username',
        'password',
        'name',
        'email',
        'mobile',
        'is_admin',
        'avatar',
        'role',
        'sources',
        'lasttime',
        'lastip',
        'remember_token',
        'creator_id',
        'is_forbidden',
    ];

//    protected $attributes = [
//        'role' => [],
//    ];

    protected $hidden = [
        'password',
    ];

    protected $casts = [
        'role' => 'array',
        'sources' => 'json',
    ];

    const MANGER_UN_FORBIDDEN = 0;
    const MANAGER_FORBIDDEN = 1;

    /**
     * 为数组 / JSON 序列化准备日期。
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联角色
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany('App\Models\Role', 'role_users', 'user_id', 'role_id');
    }

    /**
     * 关联创建角色
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function createdRoles()
    {
        return $this->hasMany(\App\Models\Role::class, 'creator_id', 'id');
    }

    public function creator()
    {
        return $this->hasOne(\App\Models\Manager::class, 'id', 'creator_id');
    }

    /**
     * 关联 oauth
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function oauthRelations()
    {
        return $this->hasMany(\App\Models\ManagerOauthRelation::class);
    }

    /**
     * @param $username
     * @return Builder|Model|object|null
     */
    public function findForPassport($username)
    {
        return $this->where('username', $username)->first();
    }

    /**
     * 修改器 密码
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    /**
     * 创建的角色ID
     * @return array
     */
    public function getCreatedRoleIdsAttribute(): array
    {
        return $this->createdRoles()->pluck('id')->toArray();
    }

    /**
     * 获取当前用户可管理的角色（当前账号角色+当前账号创建的所有角色）
     * @return array
     */
    public function getAllowedRoles()
    {
        return array_unique(array_merge($this->created_role_ids, $this->role));
    }
}
